<?php

class CategoryController extends AController
{
    public $_model;

    public function actionView($id)
    {
        $sort = 'price asc';
        $sortDate = Yii::app()->request->getParam('date');
        $sortPrice = Yii::app()->request->getParam('price');

        if ($sortDate)
            $sort = 'created_time ' . $sortDate;
        if ($sortPrice)
            $sort = 'price ' . $sortPrice;

        $criteria = new CDbCriteria();
        $criteria->condition = 'category_id=:category_id';
        $criteria->params = array(':category_id' => $id);
        $criteria->order = $sort;

        $item_count = Products::model()->count($criteria);

        $pages = new CPagination($item_count);
        $pages->setPageSize(Yii::app()->params['listPerPage']);
        $pages->applyLimit($criteria); // the trick is here!

        $this->render('view', array(
            'category' => $this->loadModel(),
            'model' => Products::model()->findAll($criteria), // must be the same as $item_count
            'item_count' => $item_count,
            'page_size' => Yii::app()->params['listPerPage'],
            'items_count' => $item_count,
            'pages' => $pages,
            'sort' => $sort
        ));
    }

    public function actionCreate()
    {
        $model = new Category;

        $this->performAjaxValidation($model);
        if (isset($_POST['Category'])) {
            $model->attributes = $_POST['Category'];
            if (isset($_POST['Category']['listSubmenu'][0]) && $_POST['Category']['listSubmenu'][0] != 0) {
                $model->list_sub_id = implode($_POST['Category']['listSubmenu'], ',');
            } else {
                $model->list_sub_id = "";
            }
            if ($model->save()) {
                $this->redirect(array('/admin/category/admin'));
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    public function actionUpdate()
    {
        $model = $this->loadModel();
        $subCat = Category::model()->findAll('parent_id = ' . $model->category_id);
        $subCatId = array();
        if ($subCat) {
            foreach ($subCat as $cat) {
                $subCatId[] = $cat->sub_id;
            }
        }

        $this->performAjaxValidation($model);

        if (isset($_POST['Category'])) {
            $model->attributes = $_POST['Category'];
            $model->attributes = $_POST['Category'];
            if (isset($_POST['Category']['listSubmenu'][0]) && $_POST['Category']['listSubmenu'][0] != 0) {
                $model->list_sub_id = implode($_POST['Category']['listSubmenu'], ',');
            } else {
                $model->list_sub_id = "";
            }
            if ($model->save()) {
                $this->redirect(array('/admin/category/admin'));
            }
        }

        $this->render('update', array(
            'model' => $model, 'subCatId' => $subCatId
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     */
    public function actionDelete($id)
    {
        $listProduct = Products::model()->findAll("category_id ='" . $id . "'");

        if($listProduct) {
            foreach($listProduct as $product) {
                $listOrder = OrderPosition::model()->findAll("product_id ='" . $product->product_id . "'");
                if($listOrder) {
                    OrderPosition::model()->deleteAll("product_id ='" . $product->product_id . "'");
                    foreach($listOrder as $order) {
                        Order::model()->deleteAll("order_id ='" . $order->order_id . "'");
                    }
                }
                Image::model()->deleteAll("product_id ='" . $product->product_id . "'");
            }
        }
        Products::model()->deleteAll("category_id ='" . $id . "'");
        $this->loadModel()->delete();

        Yii::app()->user->setFlash('message', "Xóa danh mục menu thành công!");

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_POST['ajax']))
            $this->redirect(array('/admin/category/admin'));

    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $dataProvider = new CActiveDataProvider('Category');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        $model = new Category('search');
        if (isset($_GET['Category']))
            $model->attributes = $_GET['Category'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     */
    public function loadModel()
    {
        if ($this->_model === null) {
            if (isset($_GET['id']))
                $this->_model = Category::model()->findbyPk($_GET['id']);
            if ($this->_model === null)
                throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $this->_model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'category-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    /**
     * Manages all models.
     */
    public function actionSubcat($catId)
    {
        $string = "<option value=''>Không có danh mục con</option>";
        $subCat = Category::model()->findByPk($catId);
        if ($subCat) {
            if ($subCat->list_sub_id) {
                $listSubId = explode(',', $subCat->list_sub_id);
                foreach ($listSubId as $subId) {
                    $sub = Category::model()->findByPk($subId);
                    if ($subId == $catId) {
                        $string .= "<option selected='selected' value='" . $subId . "'>" . $sub->title . "</option>";
                    } else {
                        $string .= "<option value='" . $subId . "'>" . $sub->title . "</option>";
                    }
                }
            }
        }
        echo $string;
        die;
    }
    
    /*
     * ajax update order category
     */
    public function actionUpdateOrder() 
    {
        if(isset($_POST['catId']))
        {
            $categoryModel = new Category();
            if($_POST['down'] == 1) 
                $result = $categoryModel->updateOrderDown($_POST['catId']);
            else
                $result = $categoryModel->updateOrderUp($_POST['catId']);
        }
    }
    
    /*
     * save order subcategory
     */
    public function actionSaveOrder() 
    {
       if(is_array($_POST)) { 
            foreach($_POST['id'] as $key=>$id) {
                Category::model()->updateByPk($id, array('order'=>$_POST['order'][$key]));
            }
        }
        
        $this->redirect('/admin/category/admin');
    }
}
